<template>
    <section class="liveInteractive">
        <div class="last">
            <img @click='goBack' src="../../image/icon_closed.png" width='32' alt="">
        </div>
          
  
          <!-- <div id="room-urls" style="text-align: center;display: none;background: #F1EDED;margin: 15px -10px;border: 1px solid rgb(189, 189, 189);border-left: 0;border-right: 0;"></div> -->
        <!-- </div> -->
      <!-- <div class="make-center" id="broadcast-viewers-counter"></div> -->
        <video id="video-preview" controls="" loop="" v-show="videoShow"></video>
        <div class="btn" v-show="buttonShow">
            <button id="open-or-join" @click="openorjoin" v-show="buttonShow">观看直播</button>
        </div>
        <div class="chat">
            <div class="title" v-show="videoShow">
                <span>主播: {{live_roomObj.username}}</span>
                <p>
                    <!-- <img src="../../img/33.jpg" width="20" height="20" />
                    <img src="../../img/4de25b51-1ab1-4c70-8a82-e765a0c7efbb.jpg" width="20" height="20" />
                    <img src="../../img/1.jpg" width="20" height="20" /> -->
                     <!-- 在线人数: {{onlineNum}}人 -->
                </p>
            </div>
            <div class="border-6"></div>
            <div class="box" id='box'>
                <!-- <Loadmore
                    :bottom-method="loadBottom"
                    :bottom-all-loaded="allLoaded"
                    ref="loadmore"
                    :autoFill="false"
                > -->
                  <ul>
                      <li v-for='(item,index) in charList' :key='index' :class='obj.userid == item.userid?"me":"other"'>
                          <a>{{item.userid}}</a>
                          <div>
                              <i></i>
                              <p>{{item.content}}</p>
                          </div>
                      </li>
                  </ul>
                <!-- </Loadmore> -->
            </div>
            
        </div>
        <div class="mc">
            <div class='bottom'>
                <div class="input">
                    <input type="text" placeholder="我也来聊几句..." v-model='obj.content'>
                    <span class='send' @click.stop='commentFun'>发送</span>
                </div>
            </div>
        </div>
    </section>
</template>
<script>
    import {Loadmore} from 'mint-ui';
    import {formatDate} from '../../common/date.js'
    var enableRecordings = false;
    var connection = new RTCMultiConnection(null, {
        useDefaultDevices: true // if we don't need to force selection of specific devices
    });
    connection.enableScalableBroadcast = true;
    connection.maxRelayLimitPerUser = 1;
    connection.autoCloseEntireSession = true;
    connection.socketURL = 'https://www.allbim.cn/';
    connection.socketMessageEvent = 'scalable-media-broadcast-demo';
    export default {
        data() {
            return {
                buttonShow:true,
                videoShow:false,
                isShowMc: false,  //是否显示评价
                bcid: '',
                onlineNum: 0,  //在线人数
                live_roomObj: {}, //直播间详情
                obj: {
                    userid: localStorage.getItem('loginMobile'),
                    content: '',    //评价内容     
                },
                charList: [], //聊天记录
                sentPage:{
                    page : 1,//分页累加
                },//接口入参
                totalNum: 0, //总数据条数
                allLoaded: false,                   //分页数据是否已经加载完毕
                scrollTop: 0,
            }
        },
        components: {
            Loadmore
        },
        methods: {
            commentFun() {
                if(!this.sendMessage) {
                    this.$utils._toast('请先观看直播');
                } else {
                    if(this.obj.content&&this.obj.userid) {
                        this.sendMessage();
                        this.$nextTick(function () {
                            var el_height = $('.box').prop("scrollHeight")+80;
                            // console.log('-------22',el_height);
                            this.scrollTop = el_height;
                            $(".box").scrollTop(this.scrollTop);
                        })
                        
                    } else {
                        this.$utils._toast('聊天不可为空');
                    }
                    
                    
                }
            },
            //获取主播间详情
            getGradeScore() {
                this.$api.get(this.$api.baseURLSchool,"select_cid/view_live_room_user/"+this.bcid,{},r => {
                    //   console.log(r);
                    if(r.data.ret == 1) {
                        this.live_roomObj = r.data.info;
                    }
                },err => {
                    console.log(err);
                })
            },
            //评价上拉加载
            loadBottom() {
                (this.sentPage.page)++;
                setTimeout(() => {
                    // this.getCommentList(this.sentPage);
                }, 20);
                if(this.totalNum == this.list.length) {
                    this.allLoaded = true;
                }
                this.$refs.loadmore.onBottomLoaded();
            },
            init() {
                this.bcid = this.$route.query.bcid;
            },
            goBack() {
                
                if(window.connection) {
                    try {
                        window.connection.attachStreams.forEach(function(stream) {
                            stream.stop();
                        });

                        window.connection.close();
                    }
                    catch(e){}

                    window.connection = null;
                }
                document.getElementById('video-preview').pause();
                document.getElementById('video-preview').src = null;
                location.reload();
               
                // this.$router.back();
               
                
               
                
            },
            
            callbackFn:function(bcid){
                var _this = this;
                var broadcastId= bcid;
                connection.session = {
                    audio: true,
                    video: true,
                    oneway: true
                };
                var socket = connection.getSocket();
                socket.emit('check-broadcast-presence', broadcastId, function(isBroadcastExists) {
                    if(!isBroadcastExists) {
                        // the first person (i.e. real-broadcaster) MUST set his user-id
                        // connection.userid = broadcastId;
                        _this.$utils._toast('主播不在线');
                        _this.buttonShow = true;
                        return;
                    }
            
                    console.log('check-broadcast-presence', broadcastId, isBroadcastExists);
            
                    socket.emit('join-broadcast', {
                        broadcastId: broadcastId,
                        userid: connection.userid,
                        typeOfStreams: connection.session
                    });
                });
                this.sendMessage = function() {
                    if(_this.obj.content&&_this.obj.userid) {
                        socket.emit('scalable-broadcast-message',broadcastId, _this.obj);  
                        _this.obj.content = '';
                    } else {
                        _this.$utils._toast('聊天不可为空');
                    }
                }      
                
            },
            openorjoin:function(){
                var _this = this;
                if(this.bcid == null || this.bcid == '') {
                    _this.$utils._toast('房间号不可为空');
                    return false;
                }
                this.buttonShow=false;
                this.videoShow=true;
                // alert(this.bcid);
                app.checkAndroidPermissions(this.callbackFn(this.bcid));
            }
        },
        created() {
            this.init();
            this.getGradeScore();
        
        },
        //history模式下 返回会触发
        beforeRouteEnter(to, from, next) {
            next();
        },
        beforeRouteLeave(to, from, next) {
            next();
        },
        mounted() {
            var _this = this;
            connection.connectSocket(function(socket) {
                // this event is emitted when a broadcast is already created.
                socket.on('join-broadcaster', function(hintsToJoinBroadcast) {
                    console.log('join-broadcaster', hintsToJoinBroadcast);
                
                    connection.session = hintsToJoinBroadcast.typeOfStreams;
                    connection.sdpConstraints.mandatory = {
                        OfferToReceiveVideo: !!connection.session.video,
                        OfferToReceiveAudio: !!connection.session.audio
                    };
                    connection.broadcastId = hintsToJoinBroadcast.broadcastId;
                    connection.join(hintsToJoinBroadcast.userid);
                });
            
                socket.on('rejoin-broadcast', function(broadcastId) {
                    console.log('rejoin-broadcast', broadcastId);
                    connection.attachStreams = [];
                    socket.emit('check-broadcast-presence', broadcastId, function(isBroadcastExists) {
                        if(!isBroadcastExists) {
                            // the first person (i.e. real-broadcaster) MUST set his user-id
                            connection.userid = broadcastId;
                        }
                        socket.emit('join-broadcast', {
                            broadcastId: broadcastId,
                            userid: connection.userid,
                            typeOfStreams: connection.session
                        });
                    });
                });
                socket.on('broadcast-stopped', function(broadcastId) {
                    // location.reload();
                    console.error('broadcast-stopped', broadcastId);
                    _this.$utils._toast('主播已离开');
                });
            
                // this event is emitted when a broadcast is absent.
                socket.on('start-broadcasting', function(typeOfStreams) {
                    console.log('start-broadcasting', typeOfStreams);
                
                    // host i.e. sender should always use this!
                    connection.sdpConstraints.mandatory = {
                        OfferToReceiveVideo: false,
                        OfferToReceiveAudio: false
                    };
                    connection.session = typeOfStreams;
                
                    // "open" method here will capture media-stream
                    // we can skip this function always; it is totally optional here.
                    // we can use "connection.getUserMediaHandler" instead
                    connection.open(connection.userid, function() {
                        showRoomURL(connection.sessionid);
                    });
                });
                socket.on('b_message',function(message) {
                    // console.log('b_message:',message);
                    _this.charList.push(message);
                    var el_height = $('.box').prop("scrollHeight");
                    console.log('-------11',el_height);
                    _this.scrollTop = el_height;
                    // alert('b_message:',message);
                });
            });
            var videoPreview = document.getElementById('video-preview');
            connection.onstream = function(event) {
                if(connection.isInitiator && event.type !== 'local') {
                    return;
                }
                if(event.mediaElement) {
                    event.mediaElement.pause();
                    delete event.mediaElement;
                }
                connection.isUpperUserLeft = false;
                videoPreview.src = URL.createObjectURL(event.stream);
                videoPreview.play();
                videoPreview.userid = event.userid;
                if(event.type === 'local') {
                    videoPreview.muted = true;
                }
                if (connection.isInitiator == false && event.type === 'remote') {
                    // he is merely relaying the media
                    connection.dontCaptureUserMedia = true;
                    connection.attachStreams = [event.stream];
                    connection.sdpConstraints.mandatory = {
                        OfferToReceiveAudio: false,
                        OfferToReceiveVideo: false
                    };
        
                    var socket = connection.getSocket();
                    socket.emit('can-relay-broadcast');
            
                    if(connection.DetectRTC.browser.name === 'Chrome') {
                        connection.getAllParticipants().forEach(function(p) {
                            if(p + '' != event.userid + '') {
                                var peer = connection.peers[p].peer;
                                peer.getLocalStreams().forEach(function(localStream) {
                                    peer.removeStream(localStream);
                                });
                                peer.addStream(event.stream);
                                connection.dontAttachStream = true;
                                connection.renegotiate(p);
                                connection.dontAttachStream = false;
                            }
                        });
                    }
            
                    if(connection.DetectRTC.browser.name === 'Firefox') {
                        // Firefox is NOT supporting removeStream method
                        // that's why using alternative hack.
                        // NOTE: Firefox seems unable to replace-tracks of the remote-media-stream
                        // need to ask all deeper nodes to rejoin
                        connection.getAllParticipants().forEach(function(p) {
                            if(p + '' != event.userid + '') {
                                connection.replaceTrack(event.stream, p);
                            }
                        });
                    }
                      
                    // Firefox seems UN_ABLE to record remote MediaStream
                    // WebAudio solution merely records audio
                    // so recording is skipped for Firefox.
                    if(connection.DetectRTC.browser.name === 'Chrome') {
                        repeatedlyRecordStream(event.stream);
                    }
                }
            };
            connection.onstreamended = function() {};
            connection.onleave = function(event) {
                if(event.userid !== videoPreview.userid) return;

                var socket = connection.getSocket();
                socket.emit('can-not-relay-broadcast');

                connection.isUpperUserLeft = true;

                if(allRecordedBlobs.length) {
                    // playing lats recorded blob
                    var lastBlob = allRecordedBlobs[allRecordedBlobs.length - 1];
                    videoPreview.src = URL.createObjectURL(lastBlob);
                    videoPreview.play();
                    allRecordedBlobs = [];
                }
                else if(connection.currentRecorder) {
                    var recorder = connection.currentRecorder;
                    connection.currentRecorder = null;
                    recorder.stopRecording(function() {
                        if(!connection.isUpperUserLeft) return;

                        videoPreview.src = URL.createObjectURL(recorder.blob);
                        videoPreview.play();
                    });
                }

                if(connection.currentRecorder) {
                    connection.currentRecorder.stopRecording();
                    connection.currentRecorder = null;
                }
            };
            var allRecordedBlobs = [];

            function repeatedlyRecordStream(stream) {
                if(!enableRecordings) {
                return;
                }
        
                connection.currentRecorder = RecordRTC(stream, {
                type: 'video'
                });
        
                connection.currentRecorder.startRecording();
        
                setTimeout(function() {
                    if(connection.isUpperUserLeft || !connection.currentRecorder) {
                        return;
                    }
                    connection.currentRecorder.stopRecording(function() {
                        allRecordedBlobs.push(connection.currentRecorder.blob);
                
                        if(connection.isUpperUserLeft) {
                            return;
                        }
                        connection.currentRecorder = null;
                        repeatedlyRecordStream(stream);
                    });
                }, 30 * 1000); // 30-seconds
            };

            function disableInputButtons() {
                document.getElementById('open-or-join').disabled = true;
                document.getElementById('broadcast-id').disabled = true;
            }
            // below section detects how many users are viewing your broadcast

            connection.onNumberOfBroadcastViewersUpdated = function(event) {
                console.log('-----------------------------',11);
                // alert("event:",event)
                if (!connection.isInitiator) return;
                _this.onlineNum = event.numberOfBroadcastViewers;
                console.log('---------------------------------',event.numberOfBroadcastViewers);
            };
        }
    }
</script>
<style lang="scss" scoped>
    .last {
          position: fixed;
          top: 10px;
          right: 10px;
          z-index: 3;
    }
    .liveInteractive{
        position: absolute;
        top: 0;
        width: 100%;
        height: 100%;
    }
    #open-or-join{
        width: 144px;
        background: linear-gradient(to bottom, #43d88a, #43d89c);;
        color: #fff;
        height: 35px;
        font-size: 17px;
        border-radius: 16px;
        text-align: center;
        border: none;
        position: absolute;
        top: 50%;
        left: 50%;
        transform: translate(-50%,-50%);
    }
    .btn {
        background: rgba(0,0,0,.9);
    }
    video,.btn {
        object-fit: fill;
        width: 100%;
        max-width: 100%;
        height: 300px;
        position: absolute;
        top:0;
        left: 0;
        /* height: 100%; */
    }
    input,
    select {
        font-weight: normal;
        padding: 2px 4px;
        text-decoration: none;
        display: inline-block;
        text-shadow: none;
        font-size: 16px;
        outline: none;
    }
  
    .make-center {
        text-align: center;
    }
  
    input, select {
        font-family: Myriad, Arial, Verdana;
        font-weight: normal;
        border-top-left-radius: 3px;
        border-top-right-radius: 3px;
        border-bottom-right-radius: 3px;
        border-bottom-left-radius: 3px;
        padding: 4px 12px;
        text-decoration: none;
        color: rgb(27, 26, 26);
        display: inline-block;
        box-shadow: rgb(255, 255, 255) 1px 1px 0px 0px inset;
        text-shadow: none;
        background: -webkit-gradient(linear, 0% 0%, 0% 100%, color-stop(0.05, rgb(241, 241, 241)), to(rgb(230, 230, 230)));
        font-size: 20px;
        border: 1px solid red;
        outline:none;
        vertical-align: middle;
    }
    select {
        height: 35px;
        margin: 0 5px;
    }
  
     input:hover, select:hover {
        background: -webkit-gradient(linear, 0% 0%, 0% 100%, color-stop(5%, rgb(221, 221, 221)), to(rgb(250, 250, 250)));
        border: 1px solid rgb(142, 142, 142);
    }
  
    input:active, select:active, input:focus, select:focus {
        background: -webkit-gradient(linear, 0% 0%, 0% 100%, color-stop(5%, rgb(183, 183, 183)), to(rgb(255, 255, 255)));
        border: 1px solid rgb(142, 142, 142);
    }
    iput[disabled], select[disabled] {
        background: rgb(249, 249, 249);
        border: 1px solid rgb(218, 207, 207);
        color: rgb(197, 189, 189);
    }
    input, input:focus, input:active {
        background: white;
    }
</style>
  